package com.ywl.study.transaction.netty;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ywl.study.transaction.transaction.DistirctTransactionManager;
import com.ywl.study.transaction.transaction.DistrictTransaction;
import com.ywl.study.transaction.transaction.TransactionType;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class NettyClientHandler extends ChannelInboundHandlerAdapter {

    private ChannelHandlerContext context;

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("netty client channelActive");
       context=ctx;
    }


    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        log.info("netty client接受数据: "+msg.toString());
        JSONObject jsonObject= JSON.parseObject((String)msg);

        String groupId=jsonObject.getString("groupId");//事务组id
        String command=jsonObject.getString("command");
        log.info("接受到command:"+command);
        //根据groupId获得本地分支事务
        DistrictTransaction transaction=DistirctTransactionManager.getTransaction(groupId);
        if("rollback".equals(command)){
            transaction.setTransactionType(TransactionType.ROLLBACK);
        }else{
            transaction.setTransactionType(TransactionType.COMMIT);
        }
        log.info("唤醒锁.....");
        //唤醒
        transaction.getTask().siganlTask();
    }
}

























